﻿using Abp.AutoMapper;
using Abp.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.BusinessLogic.TicketLogic.Dtos;
using Yozeev.SystemConfig;

namespace Yozeev.Controllers.Stats.Detail
{
    public class StatDetail : IGetDetailable
    {
        private readonly IRepository<Activity, Guid> _activityRep;

        private readonly IRepository<Source, Guid> _sourceRep;

        private readonly IRepository<TicketDetail, Guid> _ticketDetailRep;

        private readonly IRepository<Schedule, Guid> _scheduleRep;

        private readonly IRepository<PayMethod, Guid> _paymethodRep;

        private readonly IRepository<Account, Guid> _accountRep;

        public StatDetail(IRepository<Account, Guid> accountRep,
            IRepository<Activity, Guid> activityRep,
            IRepository<Source, Guid> sourceRep,
            IRepository<TicketDetail, Guid> ticketDetailRep,
            IRepository<Schedule, Guid> scheduleRep,
            IRepository<PayMethod, Guid> paymethodRep)
        {
            _accountRep = accountRep;
            _paymethodRep = paymethodRep;
            _scheduleRep = scheduleRep;
            _ticketDetailRep = ticketDetailRep;
            _sourceRep = sourceRep;
            _activityRep = activityRep;
        }

        public List<AccountDetailDto> GetDetailByActivities(IQueryable<Activity> activities)
        {
            var activityIds = activities.Select(a => a.Id).ToList();
            var tickets = _ticketDetailRep.GetAll()
                .Where(t => activityIds.Contains(t.ActivityDetail.ActivityId));

            List<AccountDetailDto> result = new List<AccountDetailDto>();
            foreach (var activity in activities)
            {
                List<TicketDetail> t = tickets.Where(m
                    => m.ActivityDetail.Activity.Id.Equals(activity.Id)).ToList();
                var ticketDtos = t.MapTo<List<TicketDetailListDto>>();
                var accountDetail = activity.MapTo<AccountDetailDto>();
                accountDetail.Tickets = ticketDtos;
                accountDetail.Source = _sourceRep.GetAll().Where(s => s.Id == accountDetail.SourceId).FirstOrDefault();
                accountDetail.Schedule = _scheduleRep.GetAll().Where(s => s.Id == accountDetail.ScheduleId).FirstOrDefault();
                accountDetail.PayMethod = _paymethodRep.GetAll().Where(p => p.Id == accountDetail.PayMethodId).FirstOrDefault();
                accountDetail.Account = _accountRep.GetAll().Where(a => a.Id == accountDetail.AccountsId).FirstOrDefault();
                result.Add(accountDetail);
            }

            return result;
        }
    }
}
